package com.yf.mediaserver.gb.sip.conf;

import java.util.Properties;

import javax.sip.SipStack;

import gov.nist.core.ServerLogger;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.stack.SIPTransactionStack;

public class ServerLoggerImpl implements ServerLogger {

    private boolean showLog = true;

    private SIPTransactionStack sipStack;

    protected StackLogger stackLogger;

    @Override
    public void closeLogFile() {

    }

    public static String messageFormat(SIPMessage message, String from, String to, boolean sender){
        if(sender){
            return String.format("[%s]发送至:[%s] -> 消息。\n>>>>>>>>>>>>>>>>>>>>>>>\n%s\n<<<<<<<<<<<<<<<<<<<<<<<",from,to,message);
        }
        return String.format("[%s]接收来自:[%s] -> 消息。\n>>>>>>>>>>>>>>>>>>>>>>>\n%s\n<<<<<<<<<<<<<<<<<<<<<<<",to,from,message);
    }


    @Override
    public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
        if (!showLog) {
            return;
        }
        this.stackLogger.logInfo(messageFormat(message,from,to,sender));

    }

    @Override
    public void logMessage(SIPMessage message, String from, String to, String status, boolean sender, long time) {
        if (!showLog) {
            return;
        }
        this.stackLogger.logInfo(messageFormat(message,from,to,sender));
    }

    @Override
    public void logMessage(SIPMessage message, String from, String to, String status, boolean sender) {
        if (!showLog) {
            return;
        }
        this.stackLogger.logInfo(messageFormat(message,from,to,sender));
    }

    @Override
    public void logException(Exception ex) {
        if (!showLog) {
            return;
        }
        this.stackLogger.logException(ex);
    }

    @Override
    public void setStackProperties(Properties stackProperties) {
        if (!showLog) {
            return;
        }
        String TRACE_LEVEL = stackProperties.getProperty("gov.nist.javax.sip.TRACE_LEVEL");
        if (TRACE_LEVEL != null) {
            showLog = true;
        }
    }

    @Override
    public void setSipStack(SipStack sipStack) {
        if (!showLog) {
            return;
        }
        if(sipStack instanceof SIPTransactionStack) {
            this.sipStack = (SIPTransactionStack)sipStack;
            this.stackLogger = this.sipStack.getStackLogger();
        }
    }
}
